package com.example.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.service.AdminService;
import com.example.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    AdminService adminService;

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            token = request.getParameter("token");
        }
        if(StrUtil.isBlank(token)){
            throw new CustomerException(401,"token验证失败，请重新登录或更换其它账号");
        }
        Account account = null;
        try{
            String audience = JWT.decode(token).getAudience().get(0);
            String[] split = audience.split("-");
            String userId = split[0];
            String role = split[1];
            if("ADMIN".equals(role)){
                account = adminService.selectById(userId);
            }else if("USER".equals(role)){
                account = userService.selectById(userId);
            }
        }catch (Exception e){
            throw new CustomerException(401,"token解析异常");
        }
        if(account == null){
            throw new CustomerException(401,"token解析失败");
        }
        try {
            JWT.require(Algorithm.HMAC256(account.getPassword())).build().verify(token);
        }catch (Exception e){
            throw new CustomerException(401,"token验证失败");
        }
        return  true;
    }
}
